import 'dart:convert';
import 'package:report_sdk/src/models/event.dart';
import 'package:report_sdk/src/reporter/reporter.dart' as impl;
import 'package:report_sdk/src/config/report_sdk_config.dart';
import 'dart:js_interop';

import 'package:web/web.dart' as web;

class Reporter implements impl.Reporter {
  final ReportSdkConfig config;
  // 私有构造函数
  Reporter({required this.config});

  @override
  Future<bool> sendBatch(List<Event> events) async {
    final nowTimestampMicros = config.now().microsecondsSinceEpoch.toString();
    final requestBody = {
      "user_id": config.userId,
      "timestamp_micros": nowTimestampMicros,
      "events": events.map((event) => event.toJson()).toList(),
    };
    final jsonString = jsonEncode(requestBody);
    // 使用新的js_interop方式解析JSON
    final jsRequestBody = jsonString.toJS;

    return web.window.navigator.sendBeacon(config.serverUrl, jsRequestBody);
  }

  @override
  void dispose() {}
}
